package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Banner;
import cn.wolfcode.wolf2world.query.BannerQueryObject;
import cn.wolfcode.wolf2world.repository.BannerRepository;
import cn.wolfcode.wolf2world.service.BannerService;
import cn.wolfcode.wolf2world.utils.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/19 18:31
 */
@Service
public class BannerServiceImpl implements BannerService {
    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }
    @Override
    public void insert(Banner banner) {
        banner.setId(null);
        bannerRepository.insert(banner);
    }
    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }
    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }
    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    /**
     * 高级查询
     * @return
     */
    @Override
    public Page<Banner> query(BannerQueryObject qo) {
        Query query = new Query();


        return DBHelper.getPage(mongoTemplate,query,qo,Banner.class, Sort.Direction.ASC,"_id");
    }

    /**
     * 保存/更新
     * @param banner
     */
    @Override
    public void saveOrUpdate(Banner banner) {
        if(banner.getId() != null) {
            this.update(banner);
        }else {
            this.insert(banner);
        }
    }

    /**
     * 根据类型查找前五条
     * @param typeTravel
     * @return
     */
    @Override
    public List<Banner> findByType(int typeTravel) {
        Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"sequence");

        return  bannerRepository.findByType(typeTravel,pageable);
    }


}
